package com.chinaedu.oc.action.exceptionHandler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.chinaedu.oc.constant.Constant;
import com.chinaedu.oc.po.dto.PubOutputDto;
import com.chinaedu.oc.util.common.JsonUtil;
import com.chinaedu.oc.util.http.HttpRequestException;

/**
 * 统一异常处理
 * @Description: TODO
 * @author A18ccms a18ccms_gmail_com 
 * @date 2017年5月26日 下午1:40:53 
 *
 */
public class MyExceptionHandler implements HandlerExceptionResolver {
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		
		/*  使用response返回    */  
        response.setStatus(HttpStatus.OK.value()); //设置状态码  
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType  
        response.setCharacterEncoding("UTF-8"); //避免乱码  
        response.setHeader("Cache-Control", "no-cache, must-revalidate");  
		
        
        ex.printStackTrace();
        
        PubOutputDto out = new PubOutputDto();
		// 根据不同错误转向不同页面
		if (ex instanceof HttpRequestException) {
			
			HttpRequestException h = (HttpRequestException) ex;
			out.setStatus(Constant.FALSE);
			out.setMsg(h.getErrorMsg());
		}else if(ex instanceof java.lang.IllegalArgumentException){
			out.setMsg("参数错误");
			out.setStatus(false);
		}else{
			out.setStatus(Constant.FALSE);
			out.setMsg("系统错误");
		}
		
		try {
			response.getWriter().print(JsonUtil.toJson(out).toJSONString());
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}		
		
		return new ModelAndView();
	}

}
